 
#include <map>
#include <sstream>
#include <vector>
#include <sys/stat.h>
#include "aclHandler.h"
#include "configParser.h"
#include "Regex_Host_Parser.h"
#include "Debug.h"

aclHandler * aclHandler::_instance = NULL;

/*
aclHandler * aclHandler::Instance(const char *confFile)
{
	if(confFile == NULL || strlen(confFile) < 4)
		return _instance;
       
	if (NULL == _instance )
	{
		_instance = new aclHandler();
		if (! _instance->init(confFile) )
		{
			delete _instance;
			_instance = NULL;
		}
	}
	return _instance;
}
*/
/*
如果没有confFile,则采用内置的IP，也即仅允许来自本机的请求！
*/
aclHandler * aclHandler::Instance(const char *confFile)
{
      
	if (NULL == _instance )
	{
		_instance = new aclHandler();
		if(confFile == NULL || strlen(confFile) < 4)
			return _instance;

		_instance->init(confFile); 
	}
	return _instance;
}

bool aclHandler::init(const char * confFile)
{
   m_IPs.clear();
   struct stat sbconf;
   if ( stat( confFile, &sbconf) != 0 )
   {
           DEBUG2("file is not exist!:", confFile);
	   return false;
   }
   configParser config;
   vector < string > args = config.LoadConfInfo(confFile);
   
   HostParser hp;
   for(vector <string>::iterator iter = args.begin(); iter != args.end(); iter++)
	   hp.ParseHostString( (*iter));

   m_IPs = hp.GetIPs();
   if(m_IPs.size() > 0)
       return true;
   return false;
}

bool aclHandler::AclCheck(const char * ip)
{
   if(strstr(ip,"0.0.0.0")!=0 || strstr(ip,"127.0.0.1") != 0)
       return true;
 
   map < string,int > ::iterator iter = m_IPs.find(ip);
   if( iter != m_IPs.end() )
       return true;
   DEBUG2("check false: ip=", ip);
   return false;
}

aclHandler::~aclHandler() 
{


}

void aclHandler::Release()
{
	if (_instance )
	{
		delete _instance;
		_instance = NULL;
	}
}

void aclHandler::Print()
{
        cout<<"+++++++++++++       acl for client ip      ++++++++++++++"<<endl;
	map < string,int > ::iterator iter;
	
	for(iter = m_IPs.begin(); iter!= m_IPs.end(); iter++)
		cout<<"+\t"<< iter->first.c_str() << endl;

	iter = m_IPs.find("0.0.0.0");
	if(iter == m_IPs.end())
		cout<<"+\t0.0.0.0"<<endl;

	iter = m_IPs.find("127.0.0.1");
	if(iter == m_IPs.end())
		cout<<"+\t127.0.0.1"<<endl;

        cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl;
}
